package Greedy;

import java.util.Arrays;

/**
 * @ClassName EraseOverlapIntervals
 * @Description TODO
 * @Author lenovo
 * @Date 2023-06-21 9:44
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class EraseOverlapIntervals {

    /**
     * 435. 无重叠区间
     * 给定一个区间的集合 intervals ，其中 intervals[i] = [starti, endi] 。返回 需要移除区间的最小数量，使剩余区间互不重叠 。
     * <p>
     * 示例 1:
     * <p>
     * 输入: intervals = [[1,2],[2,3],[3,4],[1,3]]
     * 输出: 1           [[1,2],[1,3],[2,3],[3,4]]
     * *****************[[1,2],[1,2],[2,3],[3,4]]
     * *****************[[1,2],[1,3],[2,3],[3,4]]
     *
     * 1,4 2,5 3,7
     * 解释: 移除 [1,3] 后，剩下的区间没有重叠。
     * 示例 2:
     * <p>
     * 输入: intervals = [ [1,2], [1,2], [1,2] ]
     * 输出: 2
     * 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
     * 示例 3:
     * <p>
     * 输入: intervals = [ [1,2], [2,3] ]
     * 输出: 0
     * 解释: 你不需要移除任何区间，因为它们已经是无重叠的了。
     *
     * @param intervals
     * @return
     */
    public int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> {
            return Integer.compare(a[0], b[0]);
        });
        int count = 1;
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i - 1][1] > intervals[i][0]) {
                intervals[i][1] = Math.min(intervals[i - 1][1], intervals[i][1]);
                continue;
            } else {
                count++;
            }
        }
        return intervals.length - count;
    }

    public static void main(String[] args) {
        EraseOverlapIntervals eraseOverlapIntervals = new EraseOverlapIntervals();
        System.out.println(eraseOverlapIntervals.eraseOverlapIntervals(new int[][]{{1, 4}, {2, 5}, {3, 7}}));
    }
}